//
//  TTAFTClient.m
//  ShanbeiIpad
//
//  Created by 涛 田 on 12-7-23.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "TTAFTClient.h"
#import "AFJSONRequestOperation.h"

@implementation TTAFTClient

+ (TTAFTClient *)initClient{
    static TTAFTClient *_client = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _client = [[TTAFTClient alloc] initWithBaseURL:[NSURL URLWithString:URL_BASE]];
    });
    
    return _client;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    
    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    
    // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
	[self setDefaultHeader:@"Accept" value:@"application/json"];
    
    return self;
}

- (void)postPath:(NSString *)path 
      parameters:(NSDictionary *)parameters
   md5ValueArray:(NSArray *)valueArray
         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
{
    NSDate *now = [NSDate date];
    NSString *nowtimestamp = [NSString stringWithFormat:@"%f",[now timeIntervalSince1970]];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:parameters];
    NSString *md5String = [NSString stringWithFormat:@"%@%d", KEY, [nowtimestamp intValue]];
    for(int i = 0; i < [valueArray count]; i++){
        if([[valueArray objectAtIndex:i] isKindOfClass:[NSNumber class]]){
            md5String = [md5String stringByAppendingString:[NSString stringWithFormat:@"%@",[valueArray objectAtIndex:i]]];
        }else{
            md5String = [md5String stringByAppendingString:[valueArray objectAtIndex:i]];
        }
    }
    
    [params setValue:[NSString md5:md5String] forKey:@"checksum"];
    [params setValue:[NSString stringWithFormat:@"%d", [nowtimestamp intValue]] forKey:@"time"];
    
    NSLog(@"---path:%@",path);
    for(int i = 0; i < [[params allKeys] count]; i++){
        NSLog(@"---params:key:%@,value:%@\n",[[params allKeys] objectAtIndex:i],[[params allValues] objectAtIndex:i]);
    }
    
    [super postPath:path
         parameters:params 
            success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 
            failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure];
}

- (void)postPath:(NSString *)path
      parameters:(NSDictionary *)parameters
         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [super postPath:path
         parameters:parameters
            success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
            failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure];
}

- (void)getPath:(NSString *)path
      parameters:(NSDictionary *)parameters
         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
{
    [super getPath:path
         parameters:parameters
            success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
            failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure];
}

- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
                                                   path:(NSString *)path
                                          md5ValueArray:(NSArray *)valueArray
                                             parameters:(NSDictionary *)parameters
                              constructingBodyWithBlock:(void (^)(id <AFMultipartFormData>formData))block
{
    NSDate *now = [NSDate date];
    NSString *nowtimestamp = [NSString stringWithFormat:@"%f",[now timeIntervalSince1970]];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:parameters];
    NSString *md5String = [NSString stringWithFormat:@"%@%d", KEY, [nowtimestamp intValue]];
    for(int i = 0; i < [valueArray count]; i++){
        if([[valueArray objectAtIndex:i] isKindOfClass:[NSNumber class]]){
            md5String = [md5String stringByAppendingString:[NSString stringWithFormat:@"%@",[valueArray objectAtIndex:i]]];
        }else{
            md5String = [md5String stringByAppendingString:[valueArray objectAtIndex:i]];
        }
    }
    
    [params setValue:[NSString md5:md5String] forKey:@"checksum"];
    [params setValue:[NSString stringWithFormat:@"%d", [nowtimestamp intValue]] forKey:@"time"];
    
    NSLog(@"---path:%@",path);
    for(int i = 0; i < [[params allKeys] count]; i++){
        NSLog(@"---params:key:%@,value:%@\n",[[params allKeys] objectAtIndex:i],[[params allValues] objectAtIndex:i]);
    }
    
    return [super multipartFormRequestWithMethod:(NSString *)method
                                     path:(NSString *)path
                               parameters:(NSDictionary *)params
                constructingBodyWithBlock:(void (^)(id <AFMultipartFormData>formData))block];
}

- (void)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
                               delegate:(id)delegate
                                success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
{

    AFHTTPRequestOperation *operation = [super HTTPRequestOperationWithRequest:urlRequest
                                                                       success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                                                       failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure];
    [operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        if([delegate respondsToSelector:@selector(addNotice:)]){
            [delegate performSelector:@selector(addNotice:) withObject:[NSString stringWithFormat:@"已上传:%0.1f%%",
                                                                        (totalBytesWritten*1.0/totalBytesExpectedToWrite)*100]];
        }
        //(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
    }];
    [operation start];
}

- (void)HTTPRequestOperationWithUrl:(NSURL *)url
                           delegate:(id)delegate
                            success:(void (^)(AFHTTPRequestOperation *, id))success
                            failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
//    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
//    AFHTTPRequestOperation *operation = [super HTTPRequestOperationWithRequest:urlRequest
//                                                                       success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
//                                                                       failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure];
//    operation.inputStream =  [NSInputStream inputStreamWithData:[XDUser instance].voiceData];
//    operation.outputStream = [NSOutputStream outputStreamToMemory];
//    [operation start];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:3600];
    AFHTTPRequestOperation *operation = [super HTTPRequestOperationWithRequest:request
                                                                       success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                                                       failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure];
    [operation start];

}
@end
